﻿using HBase;
using hCommand;
using Net.http;
using Persistence;
using Persistence.sqlserver;
using System;

namespace WebApi {
    [FormAuthenticationFilter]

    [RoutePrefix("CoreStock")]
    public class CoreStockController : BaseApiController {
        ICoreStockServer coreStockServer = WMSDalFactray.getDal<ICoreStockServer>();
        ICSDServer csdServer = WMSDalFactray.getDal<ICSDServer>();
        [HttpPost, Route("FindPage")]
        public BaseResult FindPage([FromBody] CoreStockDto dto) {
            Page<CoreStock> info = coreStockServer.QueryCoreStockPage(dto);
            return BaseResult.Ok(info);
        }

        [HttpPost, Route("deleteStock"), ControlName("删除托盘库存")]
        public BaseResult deleteStock(CoreStock model) {
            CoreStock cs = coreStockServer.getById<CoreStock>(model.id);
            if (cs.status != (int)StockStatus.库外) {
                return BaseResult.Error("库存状态异常" + cs.status);
            }
            bool r = csdServer.deleteStock(model);
            if (r) {
                return BaseResult.Ok(true);
            } else {
                return BaseResult.Error("托盘有明细");
            }
        }


        public static object locler = new object();
        public static bool saving = false;

        [HttpPost, Route("SaveStock"), ControlName("托盘保存")]
        public BaseResult SaveStock(StockDto model) {
            if (saving) {
                return BaseResult.Error("保存堵塞请重试");
            }
            lock (locler) {
                saving = true;
                try {
                    CoreStock stock = model.main;
                    if (stock == null) {
                        return BaseResult.Error("托盘信息异常");
                    }
                    if (string.IsNullOrWhiteSpace(stock.boxCode)) {
                        return BaseResult.Error("托盘条码不可为空");
                    }
                    CoreStock cs = coreStockServer.getCoreStockByCode(stock.boxCode);
                    if (cs != null) {
                        return BaseResult.Error("条码已经存在");
                    }

                    if (stock.id == 0) {
                        stock.status = (int)StockStatus.库外;
                        stock.changeTime = DateTime.Now;
                    }
                    coreStockServer.saveOne2Many(model);
                    return BaseResult.Ok(stock);
                } finally {
                    saving = false;
                }

            }
        }



        [HttpPost, Route("DirectOutTask"), ControlName("托盘生成任务")]
        public BaseResult DirectOutTask(CoreStockDto dto) {
            TransRes res = WMSTransactionFacade.doDirectOutEngine(dto.id);
            if (res.s) {
                return BaseResult.Ok("生成成功");
            } else {
                return BaseResult.Error(res.msg);
            }
        }






    }
}